import {defineComponent, ref, watch} from 'vue';
import {Button, Collapse, Form, Input, Table} from 'ant-design-vue';
import type {TableColumnType} from 'ant-design-vue/lib/table/interface';
import {DownOutlined, UpOutlined} from '@ant-design/icons-vue';

interface TableProps<T> {
    value?: T[];
    columns: TableColumnType<T>[];
    filterMetadata?: FilterMetadata[];
    onCheckboxChange?: (selectedRows: T[]) => void; // 新增多选回调函数
}

interface FilterMetadata {
    label: string;
    key: string;
    placeholder?: string;
    type: 'input' | 'select';  // 可以根据需要扩展更多类型
}

export default defineComponent({
    name: 'AntdTableWithFilter',
    props: {
        value: {
            type: Array,
            default: () => []
        },
        columns: {
            type: Array,
            required: true
        },
        filterMetadata: {
            type: Array,
            default: () => []
        },
        onCheckboxChange: { // 定义多选回调函数的 prop
            type: Function,
            default: null
        }
    },
    emits: ['update:value', 'filter'],
    setup(props, {emit}) {
        const tableData = ref([...props.value]);
        const filterData = ref({}); // 绑定筛选区域的表单数据
        const maxVisibleRows = 3; // 最大可见行数
        const totalRows = Math.ceil(props.filterMetadata.length / 2); // 每行显示两项
        const showFilters = ref(totalRows <= maxVisibleRows); // 根据条件数量判断是否展开

        // 当前页和每页显示条数
        const currentPage = ref(1);
        const pageSize = ref(10);

        // Watch for changes from parent component (v-model)
        watch(
            () => props.value,
            (newValue) => {
                tableData.value = [...newValue];
            }
        );

        // Update v-model when table data changes
        const updateTableData = (newData: any[]) => {
            tableData.value = [...newData];
            emit('update:value', newData);
        };

        // 切换筛选区域显示状态
        const toggleFilters = () => {
            showFilters.value = !showFilters.value;
        };

        // 提交筛选条件
        const submitFilters = () => {
            emit('filter', filterData.value); // 提交筛选数据
        };

        // 动态生成筛选表单
        const renderFilters = () => {
            return (
                <Form layout="inline">
                    {props.filterMetadata.map((item) => (
                        <Form.Item label={item.label} key={item.key}>
                            {item.type === 'input' ? (
                                <Input v-model={[filterData.value[item.key], 'value']}
                                       placeholder={item.placeholder || ''}/>
                            ) : null}
                            {/* 根据 type 可扩展更多类型 */}
                        </Form.Item>
                    ))}
                    <Form.Item>
                        <Button type="primary" onClick={submitFilters}>搜索</Button>
                    </Form.Item>
                </Form>
            );
        };

        // 行号计算
        const renderRowNumber = (text: any, record: any, index: number) => {
            return ((currentPage.value - 1) * pageSize.value) + index + 1;
        };

        // 处理复选框选择变化
        const handleCheckboxChange = (selectedRowKeys: string[], selectedRows: any[]) => {
            if (props.onCheckboxChange) {
                props.onCheckboxChange(selectedRows);
            }
        };

        // 分页处理函数
        const handlePaginationChange = (page: number, size: number) => {
            currentPage.value = page;
            pageSize.value = size;
        };

        return () => (
            <div>
                {/* 可折叠筛选区域 */}
                <Collapse activeKey={showFilters.value ? ['1'] : []}>
                    <Collapse.Panel header="筛选条件" key="1" showArrow={false}>
                        {renderFilters()}
                    </Collapse.Panel>
                </Collapse>
                {totalRows > maxVisibleRows && (
                    <Button type="link" onClick={toggleFilters}>
                        {showFilters.value ? <UpOutlined/> : <DownOutlined/>} {showFilters.value ? '收起' : '展开'}
                    </Button>
                )}

                {/* 表格 */}
                <Table
                    columns={[
                        {
                            title: '#',
                            key: 'index',
                            customRender: renderRowNumber
                        },
                        {
                            title: '选择',
                            dataIndex: 'selected',
                            key: 'selected',
                            render: (text: any, record: any, index: number) => (
                                <Checkbox
                                    onChange={(e) => handleCheckboxChange([record.id], [record])} // 绑定选择变化事件
                                />
                            )
                        },
                        ...props.columns
                    ]}
                    dataSource={tableData.value}
                    rowKey="id"
                    pagination={{
                        current: currentPage.value,
                        pageSize: pageSize.value,
                        total: tableData.value.length,
                        onChange: handlePaginationChange,
                        showSizeChanger: true,
                        pageSizeOptions: ['10', '20', '30', '40'],
                    }}
                    onChange={(pagination, filters, sorter, extra) => {
                        updateTableData(extra.currentDataSource);
                    }}
                />
            </div>
        );
    }
});